package app.service.local
{
	import app.service.event.SharedObjectServiceEvent;
	import app.model.global.ApplicationModel;
	
	import com.gaiaframework.debug.GaiaDebug;
	
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;
	
	import org.robotlegs.mvcs.Actor;

	public class SharedObjectService extends Actor implements SharedObjectServiceInterface
	{
		private var so:SharedObject;

		[Inject]
		public var appModel:ApplicationModel;
		
		public function initWithName(name:String):void
		{
			so = SharedObject.getLocal(name, "/" );
			GaiaDebug.log("SharedObjectService.initWithName name = ", name);
			dispatch(new SharedObjectServiceEvent(SharedObjectServiceEvent.SHARED_OBJECT_INITIALIZED));
		}
		
		public function saveValueWithKey(value:*, key:String):void {
			GaiaDebug.log("SharedObjectService.saveValueWithKey::saving value = ", value);
			so.data[key] = value;
			
			var flushStatus:String = null;
			try 
			{
				flushStatus = so.flush();
			} 
			catch (error:Error) 
			{
				GaiaDebug.log("SharedObjectService.saveValueWithKey::Error Could not write SharedObject to disk");
			}
			
			if (flushStatus != null) 
			{
				switch (flushStatus) 
				{
					case SharedObjectFlushStatus.PENDING:
						GaiaDebug.log("SharedObjectService.saveValueWithKey::Requesting permission to save object");
						so.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
						break;
					case SharedObjectFlushStatus.FLUSHED:
						GaiaDebug.log("SharedObjectService.saveValueWithKey::Value flushed to disk");
						break;
				}
			}
		}
		
		public function clearAll():void
		{
			GaiaDebug.log("SharedObjectService.clearAll");
			so.clear();
		}
		public function clearValueWithKey(key:String):void 
		{
			GaiaDebug.log("SharedObjectService.clearValueWithKey::Cleared saved value...Reload SWF and the value should be \"undefined\"");
			delete so.data[key];
		}
		
		public function getValueWithKey(key:String):*
		{
			GaiaDebug.log("SharedObjectService.getValueWithKey = ", so.data[key]);
			return so.data[key];
		}
		
		private function onFlushStatus(event:NetStatusEvent):void 
		{
			GaiaDebug.log("SharedObjectService.onFlushStatus::User closed permission dialog");
			switch (event.info.code) {
				case "SharedObject.Flush.Success":
					GaiaDebug.log("SharedObjectService.onFlushStatus::User granted permission -- value saved");
					break;
				case "SharedObject.Flush.Failed":
					GaiaDebug.log("SharedObjectService.onFlushStatus::User denied permission -- value not saved");
					break;
			}
			so.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
		}

	}
}